<template>
  <div v-loading="loadingDiv">
    <el-dialog
      v-toggle-full="resetTableWidth"
      class="base-dialog"
      :class="{
        readonly:
          (readonly && formData[currentRecordIndex].status !== 50) ||
          pageViewMode2 === 'print',
        print: pageViewMode2 === 'print',
        zip: autoDownZip,
      }"
      :title="title"
      :visible="dialogVisible"
      :append-to-body="true"
      destroy-on-close
      align="center"
      :custom-class="customClass"
      :before-close="handleClose"
    >
      <div v-show="pageViewMode2 === 'print'" class="print-download">
        <!-- <div @click="printPdf">
          <img :src="print" />
          <span>打印</span>
        </div> -->
        <div v-show="loadpdfDataOfConvert" @click="testPrint">
          <img :src="download" />
          <span>打印</span>
        </div>
        <div v-show="loadpdfDataOfConvert" @click="downLoadPdf">
          <img :src="download" />
          <span>下载</span>
        </div>
        <!-- <div @click="testPrint">
          <img :src="download" />
          <span>导出</span>
        </div> -->
        <div
          v-if="formData.length > 1"
          class="arrow left"
          title="上一份"
          @click="changeCurrentRecordIndex('left')"
        >
          <img :src="arrow" alt="" />
        </div>
        <div
          v-if="formData.length > 1"
          class="arrow right"
          title="下一份"
          @click="changeCurrentRecordIndex('right')"
        >
          <img :src="arrow" alt="" />
        </div>
      </div>
      <!-- <div v-if="pageViewMode2 === 'print'" class="print-title print-header">
        <span>河南中油豫博检测技术有限公司</span>
        <span>{{ formData[currentRecordIndex].templateName }}</span>
      </div> -->
      <div
        id="pdfDom"
        ref="print"
        :class="{
          print: loading,
          height100: pageViewMode2 !== 'print',
          printStyle: pageViewMode2 === 'print',
        }"
      >
        <div v-if="pageViewMode2 === 'print'" class="print-title print-header">
          <span>{{ baseConfig.name }}</span>
          <span>{{ formData[currentRecordIndex].templateName }}</span>
        </div>
        <!-- <div
          v-if="pageViewMode2 === 'print'"
          style="
            font-weight: bold;

            width: 100%;
            border-bottom: 1px solid rgba(0, 0, 0, 0.85);
            color: rgba(0, 0, 0, 0.85);
            position: fixed;
            top: -100vh;
            font-weight: bold;
            font-size: 28px;
            line-height: 28px;
          "
          class="print-title print-header"
        >
          <span>河南中油豫博检测技术有限公司</span>
          <span>{{ formData[currentRecordIndex].templateName }}</span>
        </div> -->
        <el-container v-if="resetLoad" class="record-edit-form-container">
          <el-aside
            v-show="pageViewMode2 !== 'print'"
            width="278px"
            class="record-edit-form-container_aside"
          >
            <ElnTemplateSide
              ref="ElnTemplateSide"
              :form-data="formData[currentRecordIndex]"
              :page-view-mode.sync="pageViewMode2"
              :operate-type="operateType"
              :readonly="readonly"
              :required-state="requiredState"
              :detection-state="detectionState"
            />
          </el-aside>
          <el-main v-if="resetLoad" class="record-edit-form-container_main">
            <ElnTemplateSide
              v-show="pageViewMode2 === 'print'"
              class="system-user-form_pdf"
              style="width: 100%"
              :form-data="formData[currentRecordIndex]"
              :page-view-mode.sync="pageViewMode2"
              :operate-type="operateType"
              :readonly="readonly"
              :detection-state="false"
            />
            <div
              v-for="item in targetList[currentRecordIndex]"
              :key="item.id"
              class="target-card-item"
              :class="{
                readonly: readonly,
                showpdf: pageViewMode2 === 'print',
                divideInside: item.controlType === 'Image',
              }"
              :style="{ width: item.span === 12 ? '45%' : '100%' }"
            >
              <component
                :is="item.name"
                :ref="item.name"
                class="card-item"
                :params="item"
                :page-view-mode.sync="pageViewMode2"
                :is-create="operateType === 0"
                :readonly="readonly"
                @tableLoadHandle="tableLoadHandle"
              ></component>
            </div>
          </el-main>
        </el-container>
        <div
          v-show="pageViewMode2 === 'print'"
          slot="footer"
          class="dialog-footer"
          align="center"
        >
          <span class="footer-title">审批信息</span>
          <ul class="dialog-verify">
            <li
              v-for="(item, index) in reviewerList"
              :key="item.reviewerId + index"
            >
              <div
                v-if="item.creator || item.reviewerTime"
                :title="item.nodeName"
                class="verify-item"
              >
                <div class="verify-account">
                  <span v-if="!item.creator || !index" class="item-nodename">{{
                    item.nodeName
                  }}</span>
                  <img
                    v-if="item.accountSignIcon"
                    :src="item.baseImg"
                    alt="未上传签名"
                  />
                  <span v-else>{{ item.reviewerName }}</span>
                </div>
                <!-- <div
                  v-if="item.reviewerTime"
                  class="verify-account verify-date"
                >
                  <span>日期: </span>
                  <span>{{ item.reviewerTime }}</span>
                </div>
              </div> -->
              </div>
            </li>
            <!-- <li style="height: 0"></li>
            <li style="height: 0"></li> -->
          </ul>
        </div>
      </div>
      <div
        v-if="
          !readonly ||
          (readonly &&
            formData[currentRecordIndex].status === 50 &&
            pageViewMode2 !== 'print')
        "
        slot="footer"
        class="dialog-footer"
        align="center"
      >
        <el-button
          v-if="readonly && showPrintButton"
          type="primary"
          @click="changePrintPage()"
          >打印</el-button
        >

        <el-button v-if="!readonly" type="primary" @click="save(1)"
          >提交</el-button
        >
        <el-button
          v-if="!readonly && operateType !== 2 && useInterfaceStatus"
          type="primary"
          @click="save(0)"
          >暂存</el-button
        >
      </div>
    </el-dialog>
    <BaseLoading v-if="loading || tableLoad" :loading-text="loadText" />

    <iframe id="frame" ref="printIframe" style="display: none" :src="pdfStream">
    </iframe>
    <div class="pdf-footer">
      <span>第</span>
      <div class="pdf-footer-page"></div>
      <span>页 / 共</span>
      <div class="pdf-footer-page-count"></div>
      <span>页</span>
    </div>
  </div>
</template>
<script>
import {
  update,
  create,
  Getlasthuditlogbylatald,
} from "../../../api/Eln/ExperimentTemplateRecord";
import { getUserListNoPage } from "../../../api/Permission/user.js";
import { deepClone } from "../../../utils";
import { checkType } from "../../../utils/validate";
import { fileDownload, outputPDF } from "../../../utils/outPutPdf.js";
// import { outputPDF } from "../../../utils/newoutPutPdf.js"
import { leaveTime } from "@/utils/moment";
import { GetStaticImgInfo } from "@/api/Base";
// 打印功能所需依赖
// import printJS from "print-js";
// import html2Canvas from "html2canvas";
// import JsPDF from "jspdf";
import JSZip from "jszip";
import FileSaver from "file-saver";
// 图标
import print from "../../../img/print.png";
import download from "../../../img/download.png";
import arrow from "../../../img/arrow.png";
import _ from "lodash";
// 引入组件
import ElnTemplateSide from "../Components/ElnTemplateSide.vue";
const allComponents = require.context(
  "../../../components/BaseControl",
  true,
  /\.vue$/
);
const res_components = {};
allComponents.keys().forEach((item) => {
  const comp = allComponents(item);
  const name = comp.default.name;
  res_components[name] = comp.default;
});
export default {
  name: "ExperimentTemplateRecordEdit",
  components: { ...res_components, ElnTemplateSide },
  props: {
    value: {
      type: [Array, Object],
      default: () => [],
    },
    detectionState: {
      type: Boolean,
      default: false,
    },
    dialogFormVisible: {
      type: Boolean,
      default: false,
    },
    decisionEdit: {
      type: Boolean,
      default: false,
    },
    // 0 新建 1 正常编辑 2 审批编辑
    operateType: {
      type: Number,
      default: 1,
    },
    // 数据来源 0 :app 1:PC端,2:Task检测任务
    source: {
      type: Number,
      default: 1,
    },
    entrustTaskId: {
      type: String,
      default: "0",
    },
    readonly: {
      type: Boolean,
      default: false,
    },
    showPrintButton: {
      type: Boolean,
      default: true,
    },
    pageViewMode: {
      type: String,
      default: "runtime",
    },
    // 自动下载为zip格式文件
    autoDownZip: {
      type: Boolean,
      default: false,
    },
    useInterfaceStatus: {
      type: Boolean,
      default: true,
    },
    // 必填状态
    requiredState: {
      type: Boolean,
      default: true,
    },
    status: {
      type: Number,
      default: 10,
    },
    // 透明度
    transparency: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      dialogVisible: false,
      tableLoad: false,
      opacityBool: 0,
      loading: false,
      loadingDiv: false,
      loadText: "",
      resetLoad: false,
      title: "",
      customClass: "panna-dialog_big",
      pageViewMode2: "runtime", // runtime 运行时 design 设计时 pageview 预览  print 打印
      copyPageViewMode: "",
      formLabelWidth: "100px",
      print,
      download,
      arrow,
      reviewerList: [],
      zipPromise: [],
      tableLen: 0, // 表格个数
      tableLen2: 0, // 表格个数2
      targetList: [],
      defaultValueJSONType: [
        "Radio",
        "Select",
        "Checkbox",
        "MultipleSelect",
        "Table",
        "DatePicker",
      ],
      valueJSONType: [
        "Radio",
        "Select",
        "Checkbox",
        "MultipleSelect",
        "Table",
        "Image",
      ],
      formData: {
        experimentNumber: "",
        articleNumber: "",
        // sampleCategoryName: "",
        detectionItemName: "",
        creatorTime: "",
        creatorName: [],
      },
      errorMsg: {
        experimentNumber: "",
        articleNumber: "",
        // sampleCategoryName: "",
        detectionItemName: "",
        creatorTime: "",
        creatorName: "",
      },
      currentRecordIndex: 0,
      searchUserLoading: false,
      userList: [],
      pdfData: "", // 需要获取的base64串
      prefixBase64: "data:application/pdf;base64,", // base64前缀
      pdfStream: "",
      loadpdfDataOfConvert: true,
      pdfBlob: "",

      baseConfig: {},
    };
  },

  computed: {
    pdfCreatorName() {
      return (
        this.formData[
          this.currentRecordIndex
        ]?.templateContentDto.leftData.find((x) => x.code === "creatorName")
          ?.value || ""
      );
    },
  },
  watch: {
    dialogFormVisible: {
      handler(val) {
        this.dialogVisible = val;
        if (val) this.init();
      },
      immediate: true,
    },
    currentRecordIndex() {
      this.resetLoad = false;
      this.$nextTick(() => {
        this.resetLoad = true;
      });
    },
  },
  mounted() {
    const baseConfig = localStorage.getItem("eln_baseConfig");
    baseConfig && (this.baseConfig = JSON.parse(baseConfig));
    this.opacityBool = this.transparency ? 1 : 0;
  },
  methods: {
    init() {
      this.tableLen = this.tableLen2 = 0;

      if (checkType(this.value) === "Object") {
        Object.assign(this.formData, this.value);
        this.formData = [this.formData];
      } else {
        this.formData = null;
        this.formData = this.value;
      }
      this.pageViewMode2 = this.copyPageViewMode = this.pageViewMode;
      this.toggleConfigByPageViewMode();
      if (!this.formData[this.currentRecordIndex].templateContentDto) return;
      this.formData.forEach((x) => {
        // const isExisTable = false;
        const list = x.templateContentDto.centerData.filter((x) => {
          if (x.controlType === "Table") {
            x.required = false;
            // if (isExisTable) return false;
            // else {
            //   isExisTable = true;
            //   return true;
            // }
          }
          return x && x.controlType !== "Title";
        });
        list.length && this.targetList.push(list);
      });
      try {
        this.targetList.forEach((targetList) => {
          targetList.forEach((item) => {
            item.name = `Control${item.controlType}`;
            if (item.value && this.valueJSONType.includes(item.controlType)) {
              item.value = JSON.parse(item.value);
            }
            if (
              item.defaultValue &&
              this.defaultValueJSONType.includes(item.controlType)
            ) {
              item.defaultValue = JSON.parse(item.defaultValue);
            }
          });
        });
      } catch (e) {
        console.log(e);
      }
      this.formData.forEach((x) => {
        x.templateContentDto.leftData.forEach((left) => {
          switch (left.code) {
            case "templateCode":
              x["experimentNumber"] = left.value;
              break;
            case "articleNumber":
              x[left.code] = left.value;
              break;
            case "creatorName":
              x[left.code] = x.testerId || [];
              break;
            case "creatorTime":
              x[left.code] = this.operateType === 0 ? new Date() : left.value;
              break;
            default:
              break;
          }
        });
      });
      if (this.autoDownZip) {
        this.loading = true;
        this.loadText = "努力下载中...";
      }
      this.judgeTableExist();
      this.resetLoad = true;
    },
    save: _.throttle(async function (type) {
      if (!this.useInterfaceStatus) {
        var nameArr = await this.getUser();
        var originalData = deepClone(this.formData[this.currentRecordIndex]);
      }
      const runFn = async () => {
        const saveList = new Array(
          this.targetList[this.currentRecordIndex].length
        ).fill(null);
        let allControlSuccess = true;
        const promiseTable = [];
        for (const i in this.$refs) {
          if (i === "formData") continue;
          const tempRef = this.$refs[i];
          if (!Array.isArray(tempRef) || !tempRef.length) continue;
          tempRef.forEach((ref) => {
            if (ref.validate instanceof Function) {
              const refData = ref.validate();
              if (refData instanceof Promise) {
                promiseTable.push(refData);
                return;
              }
              const { controlValue, validateError } = deepClone(refData);
              validateError === true && (allControlSuccess = false);
              // 删除多余的参数
              delete controlValue.name;
              // 修改特定控件value&defaultValue数据格式
              controlValue.data = controlValue.data.filter(
                (x) => x.label !== ""
              );
              // 格式化特殊控件的value以及defaultValue值
              controlValue.value &&
                this.valueJSONType.includes(controlValue.controlType) &&
                (controlValue.value = JSON.stringify(controlValue.value));
              controlValue.defaultValue &&
                this.defaultValueJSONType.includes(controlValue.controlType) &&
                (controlValue.defaultValue = JSON.stringify(
                  controlValue.defaultValue
                ));
              const currentIdx = this.targetList[
                this.currentRecordIndex
              ].findIndex((x) => x.id === controlValue.id);
              saveList.splice(currentIdx, 1, controlValue);
            }
          });
        }
        if (!allControlSuccess) return;
        // 处理table的异步数据问题
        if (promiseTable.length) {
          const tableData = await Promise.all(promiseTable);
          tableData.forEach((x) => {
            const { controlValue } = x;
            const currentIdx = this.targetList[
              this.currentRecordIndex
            ].findIndex((v) => v.id === controlValue.id);
            controlValue.value &&
              (controlValue.value = JSON.stringify(controlValue.value));
            controlValue.defaultValue &&
              (controlValue.defaultValue = JSON.stringify(
                controlValue.defaultValue
              ));
            saveList.splice(currentIdx, 1, controlValue);
          });
        }
        const operateTypeFn = this.operateType === 0 ? create : update;
        const params = deepClone(this.formData[this.currentRecordIndex]);
        params.templateId = params.id;
        delete params.id;
        params.status = this.status;
        params.decisionEdit = this.decisionEdit;
        params.source = this.source;
        params.entrustTaskId = this.entrustTaskId;
        params.submitStatus = type;
        params.creatorId = this.$store.getters.currentUserId;
        params.detectionTime =
          this.formData[this.currentRecordIndex].createTime;
        params.testerId = this.formData[this.currentRecordIndex].creatorName;
        const leftData = params.templateContentDto.leftData;
        leftData.forEach((x) => {
          try {
            switch (x.code) {
              case "creatorTime":
                x.value = leaveTime(
                  this.formData[this.currentRecordIndex][x.code]
                );
                break;
              case "creatorName":
                x.value =
                  this.formData[this.currentRecordIndex][x.code].join(",");
                break;
              default:
                x.value = this.formData[this.currentRecordIndex][x.code];
                break;
            }
          } catch (error) {
            console.log(error);
          }
        });
        params.templateContentDto = {
          leftData: leftData,
          centerData: saveList,
        };
        if (!this.useInterfaceStatus) {
          originalData.templateContentDto = params.templateContentDto;
          for (
            let i = 0;
            i < originalData.templateContentDto.leftData.length;
            i++
          ) {
            if (
              originalData.templateContentDto.leftData[i].code === "creatorName"
            ) {
              for (let o = 0; o < nameArr.data.length; o++) {
                if (
                  nameArr.data[o].id ===
                  originalData.templateContentDto.leftData[i].value
                ) {
                  originalData.templateContentDto.leftData[i].value =
                    nameArr.data[o].name;
                }
              }
            }
          }
        }

        if (this.useInterfaceStatus) {
          this.loadingDiv = true;
          operateTypeFn(params)
            .then((res) => {
              this.loadingDiv = false;
              this.$emit("update:dialogFormVisible", false);
              this.$emit("callback", params, originalData, res.data);
            })
            .catch(() => {
              this.loadingDiv = false;
            });
          return;
        }
        this.$emit("callback", params, originalData, 0);
        this.$emit("update:dialogFormvisible", false);
      };
      if (this.pageViewMode2 !== "runtime") {
        runFn();
        return;
      }
      this.$refs.ElnTemplateSide.validate().then((val) => {
        if (!val) return;
        runFn();
      });
    }, 5000),
    // 判断当前表单是否存在表格控件
    judgeTableExist() {
      const currentFormData = this.formData[this.currentRecordIndex];
      if (!currentFormData) return;
      const tableData = currentFormData.templateContentDto?.centerData?.filter(
        (x) => x.controlType === "Table"
      );
      this.tableLen = this.tableLen2 = tableData.length;
      if (this.tableLen === 0) {
        this.autoDownZip && this.beforeDownLoadPdf();
      } else {
        this.tableLoad = true;
        this.loadText = "表格加载中...";
      }
    },
    // 表格渲染完成
    tableLoadHandle() {
      this.tableLen--;
      if (this.tableLen === 0) {
        this.tableLoad = false;
        this.autoDownZip && this.$nextTick(this.beforeDownLoadPdf);
      }
      if (this.opacityBool === 3) {
        this.handleClose();
      }
      if (this.opacityBool === 1) {
        this.opacityBool = 3;

        this.changePrintPage();
      }
    },
    // 打印页面之前
    async beforeDownLoadPdf() {
      this.loading = true;
      this.loadText = "内容较多,打印准备中...";
      Promise.all([
        Getlasthuditlogbylatald({
          Id: this.formData[this.currentRecordIndex].id,
        }),
        this.getUser(),
      ]).then((result) => {
        const res = result[0];
        const res1 = result[1] || {};
        this.reviewerList = (res.data || []).map((x, index) => {
          !x.nodeName && (x.nodeName = !index ? "校对人" : "审核人");
          const tempTime = x.reviewerTime.split(" ")[0].split("-");
          x.reviewerTime = `${tempTime[0]}年${tempTime[1]}月${tempTime[2]}日`;
          x.nodeName = x.nodeName + ":";
          return x;
        });
        // 组装检测人签名
        const creatorList = [];
        (this.formData[this.currentRecordIndex]?.testerId || []).forEach(
          (y, idx) => {
            const user = res1.data.find((v) => v.id === y);
            if (!user) return;
            if (!user.accountSignIcon) return;
            const accountSignIcon = `${user.protocol}://${user.fileDomain}/${user.fileBucket}/${user.accountSignIcon}`;
            creatorList.push({
              nodeName: "检测人:",
              creator: true,
              accountSignIcon,
              reviewerId: idx,
            });
          }
        );
        this.reviewerList = creatorList.concat(this.reviewerList);
        Promise.all(
          this.reviewerList.map((item) => {
            return this.imgDispose(item.accountSignIcon).then((baseImg) => {
              item.baseImg = baseImg;
              this.$forceUpdate();
            });
          })
        ).then(() => {
          setTimeout(() => {
            // 审批信息校对人审核人图片调整
            const divEl = document.querySelectorAll(
              ".dialog-footer .verify-account"
            );
            divEl.length &&
              divEl.forEach((x) => {
                const imgEl = x.getElementsByTagName("IMG")[0];
                if (!imgEl) return;
                if (x.offsetWidth < imgEl.offsetWidth) {
                  imgEl.style.cssText = `width:${x.offsetWidth}px;height:${
                    (x.offsetWidth / imgEl.offsetWidth) * imgEl.offsetHeight
                  }px`;
                }
              });
            if (this.$refs.ControlTable?.length) {
              const printList = [];
              this.$refs.ControlTable.forEach((x) => {
                printList.push(x.printExcel());
              });
              Promise.all(printList).then(() => {
                this.getpdf();
              });
            } else {
              this.getpdf();
            }
          }, 200);
        });
      });
    },
    imgDispose(url) {
      var imgPath = "";
      const cleanedUrl = url.replace("[", "").replace("]", "").replace('"', "");
      const regexPattern = /http:\/\/[^/]+\/[^/]+\/([^?]+)/;
      const matchs = regexPattern.exec(cleanedUrl);
      if (matchs) {
        imgPath = matchs[1];
      } else {
        imgPath = url;
      }
      return new Promise((resolve, reject) => {
        GetStaticImgInfo(imgPath)
          .then((res) => {
            resolve(res.data);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 打印pdf
    // printPdf() {
    //   this.loading = true;
    //   this.loadText = "打印准备中...";
    //   const tablePrintFn = (isExisTable) => {
    //     const cloneDom = this.$refs.print;
    //     html2Canvas(this.$refs.print, {
    //       scale: 2,
    //       dpi: window.devicePixelRatio,
    //       backgroundColor: null,
    //       width: cloneDom.offsetWidth,
    //       height: cloneDom.offsetHeight,
    //       X: 0,
    //       Y: 0,
    //       scrollX: 0, // 如果左边多个白边 设置该偏移-3 或者更多
    //       scrollY: 0,
    //       useCORS: true, // 是否使用CORS从服务器加载图像 !!!
    //       allowTaint: true, // 是否允许跨域图像污染画布  !!!
    //     }).then((canvas) => {
    //       const url = canvas.toDataURL();
    //       printJS({
    //         printable: url, // 要打印的id
    //         width: cloneDom.offsetWidth,
    //         height: cloneDom.offsetHeight,
    //         type: "image",
    //         style: "@page{size:auto;margin: 0cm 1cm 0cm 1cm;}", // portrait（竖向的）或landscape（横向的） 去除页眉页脚
    //       });
    //       this.loading = false;
    //       isExisTable && this.$refs.ControlTable[0].customFn();
    //     });
    //   };
    //   if (!this.$refs.ControlTable || !this.$refs.ControlTable.length) {
    //     this.$nextTick(tablePrintFn);
    //     return;
    //   }
    //   this.$refs.ControlTable[0].printExcel().then((res) => {
    //     tablePrintFn(true);
    //   });
    // },
    // 下载pdf
    // downLoadPdf() {
    //   return new Promise((resolve, reject) => {
    //     this.loading = true;
    //     this.loadText = "努力下载中...";
    //     const downloadFn = (isExisTable) => {
    //       const cloneDom = this.$refs.print;
    //       html2Canvas(document.querySelector("#pdfDom"), {
    //         allowTaint: true,
    //         taintTest: false,
    //         useCORS: true,
    //         X: 0,
    //         Y: 0,
    //         scrollX: 0, // 如果左边多个白边 设置该偏移-3 或者更多
    //         scrollY: 0,
    //         width: cloneDom.offsetWidth,
    //         height: cloneDom.offsetHeight,
    //         dpi: window.devicePixelRatio * 4, // 将分辨率提高到特定的DPI 提高四倍
    //         scale: 4, // 按比例增加分辨率
    //       }).then((canvas) => {
    //         // #region
    //         const contentWidth = canvas.width;
    //         const contentHeight = canvas.height;
    //         const pageHeight = (contentWidth / 592.28) * 841.89;
    //         let leftHeight = contentHeight;
    //         let position = 0;
    //         const imgWidth = 595.28;
    //         const imgHeight = (592.28 / contentWidth) * contentHeight;
    //         const pageData = canvas.toDataURL("image/jpeg", 1.0);
    //         const PDF = new JsPDF("", "pt", "a4");
    //         if (leftHeight < pageHeight) {
    //           PDF.addImage(pageData, "JPEG", 0, 0, imgWidth, imgHeight);
    //         } else {
    //           while (leftHeight > 0) {
    //             PDF.addImage(
    //               pageData,
    //               "JPEG",
    //               0,
    //               position,
    //               imgWidth,
    //               imgHeight
    //             );
    //             leftHeight -= pageHeight;
    //             position -= 841.89;
    //             if (leftHeight > 0) {
    //               PDF.addPage();
    //             }
    //           }
    //         }
    //         if (!this.autoDownZip) {
    //           PDF.save(
    //             this.formData[this.currentRecordIndex]?.templateName + ".pdf"
    //           );
    //           isExisTable && this.$refs.ControlTable[0].customFn();
    //           this.loading = false;
    //           return;
    //         }
    //         // #endregion
    //         resolve({
    //           PDF,
    //           name: this.formData[this.currentRecordIndex].templateName,
    //         });
    //         // 当前表单下载完成切换表单
    //         if (this.currentRecordIndex < this.formData.length - 1) {
    //           this.currentRecordIndex++;
    //           this.judgeTableExist();
    //         } else {
    //           this.generateZIP();
    //         }
    //       });
    //     };
    //     if (!this.$refs.ControlTable || !this.$refs.ControlTable.length) {
    //       this.$nextTick(downloadFn);
    //       return;
    //     }
    //     this.$refs.ControlTable[0].printExcel().then((res) => {
    //       downloadFn(true);
    //     });
    //   });
    // },
    downLoadPdf() {
      this.loading = true;
      this.loadText = "努力下载中...";
      this.loading = false;
      return fileDownload(
        this.pdfBlob,
        this.formData[this.currentRecordIndex].templateName,
        this.autoDownZip
      );
    },
    // 下载pdf
    // baseData是后端传来的base64,fileName是文件名
    // fileDownload(baseData, fileName) {

    //   // const URL = dataURLtoBlob(baseData.substring(baseData.indexOf(',') + 1));
    //   var reader = new FileReader();
    //   reader.readAsDataURL(baseData);
    //   reader.onload = function (e) {
    //     // 兼容IE
    //     if (window.navigator.msSaveOrOpenBlob) {
    //       var bstr = atob(e.target.result.split(",")[1]);
    //       var n = bstr.length;
    //       var u8arr = new Uint8Array(n);
    //       while (n--) {
    //         u8arr[n] = bstr.charCodeAt(n);
    //       }
    //       var blob = new Blob([u8arr]);
    //       window.navigator.msSaveOrOpenBlob(blob, fileName);
    //     } else {
    //       // 转换完成，创建一个a标签用于下载
    //       const a = document.createElement('a');
    //       a.download = fileName; // 这里写你的文件名
    //       a.href = e.target.result;
    //       document.body.appendChild(a)
    //       a.click();
    //       document.body.removeChild(a)

    //     }
    //   }
    // },

    // 下载为zip文件
    generateZIP() {
      Promise.all(this.zipPromise).then(async (pdfs) => {
        const zip = new JSZip();
        const nameGather = [];
        pdfs.forEach(async (item) => {
          const { PDF } = item;
          let { name } = item;
          // 查看下载pdf文件名字是否重复
          const nameRepeat = nameGather.findLast((x) => {
            if (!x.includes(name)) return false;
            if (x === name) return true;
            const splitArr = x.split(name);
            return splitArr[1] && splitArr[1].match(/^\([0-9]+\)$/g);
          });
          if (nameRepeat) {
            const nameOrder =
              nameRepeat === name
                ? 0
                : nameRepeat.split(name)[1].replace("(", "").replace(")", "");
            name += `(${Number(nameOrder) + 1})`;
          }
          nameGather.push(name);
          await zip.file(`${name}.pdf`, PDF); // .output("blob")
        });
        // 手动修复本地时区和UTC时区的偏移量
        for (const i in zip.files) {
          const file = zip.files[i];
          const date = file.date;
          date.setHours(date.getHours() + 8);
          file.date = date;
        }
        zip
          .generateAsync({
            type: "blob",
            compression: "DEFLATE",
            compressionOptions: {
              level: 9,
            },
          })
          .then((content) => {
            const date = new Date();
            const currentDate =
              date.getFullYear() +
              "" +
              (date.getMonth() + 1 < 10
                ? `0${date.getMonth() + 1}`
                : date.getMonth() + 1) +
              (date.getDate() < 10 ? `0${date.getDate()}` : date.getDate());
            // 1. 取出浏览器存储record_batch_down_order
            // 2. 存在：判断最后一次存储日期是否是今天，是的话进行取值  不是的话取值为0
            //    不存在：取值为0
            // 3. 存储到本地
            let currentOrder = 0;
            const storageData = localStorage.getItem("record_batch_down_order")
              ? JSON.parse(localStorage.getItem("record_batch_down_order"))
              : null;
            storageData &&
              storageData.date === currentDate &&
              (currentOrder = storageData.order);

            FileSaver.saveAs(
              content,
              `原始记录${currentDate}-${++currentOrder}.zip`
            );

            localStorage.setItem(
              "record_batch_down_order",
              JSON.stringify({
                order: currentOrder,
                date: currentDate,
              })
            );
            this.loading = false;

            this.handleClose();
          });
      });
    },
    // jsPDF + html2canvas A4分页截断
    async testPrint() {
      this.$nextTick(this.$refs.printIframe.contentWindow.print());
    },
    //  二进制格式
    dataURItoBlob(dataURI) {
      // base64 解码
      const byteString = window.atob(dataURI.split(",")[1]);
      let mimeString = dataURI.split(",")[0];
      mimeString = mimeString.split(":")[1];
      const ab = new ArrayBuffer(byteString.length);
      const ia = new Uint8Array(ab);
      for (let i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
      }
      return new Blob([ab], { type: mimeString });
    },
    async getpdf() {
      this.pdfData = await this.getPdfdata();
      this.pdfBlob = this.dataURItoBlob(this.pdfData);
      const myUrl = URL.createObjectURL(this.pdfBlob);
      this.pdfStream = myUrl;
      if (!this.autoDownZip) {
        this.loading = false;
        return;
      }
      this.zipPromise.push(this.downLoadPdf());
      if (this.currentRecordIndex < this.formData.length - 1) {
        this.currentRecordIndex++;
        this.judgeTableExist();
      } else {
        this.generateZIP();
      }
    },
    async getPdfdata() {
      // return await outputPDF({
      //   element: this.$refs.print,
      //   contentWidth: 550,
      //   contentHeight: 800,
      //   outputType: 'datauristring',
      //   filename: 'document.pdf',
      //   header: document.querySelector('.print-header'),
      //   footer: document.querySelector('.pdf-footer'),

      // })
      return await outputPDF({
        element: this.$refs.print,
        contentWidth: 550,

        header: document.querySelector(".print-header"),
        footer: document.querySelector(".pdf-footer"),
      });
    },
    // 切换到打印页面
    async changePrintPage() {
      this.pageViewMode2 = "print";
      await this.toggleConfigByPageViewMode();
    },
    async changeCurrentRecordIndex(direction) {
      if (direction === "left") {
        this.currentRecordIndex > 0 && this.currentRecordIndex--;
        this.title = `共${this.formData.length}份，第${
          this.currentRecordIndex + 1
        }份`;
        return;
      }
      this.currentRecordIndex < this.formData.length - 1 &&
        this.currentRecordIndex++;
      this.title = `共${this.formData.length}份，第${
        this.currentRecordIndex + 1
      }份`;
    },
    // 根据不同的模式切换参数
    async toggleConfigByPageViewMode() {
      switch (this.pageViewMode2) {
        case "runtime":
          this.title =
            (!this.operateType ? "新建" : this.readonly ? "查看" : "编辑") +
            this.formData[this.currentRecordIndex].templateName;
          break;
        case "print":
          this.title = `共${this.formData.length}份，第${
            this.currentRecordIndex + 1
          }份`;
          !this.autoDownZip && this.beforeDownLoadPdf();
          break;
        default:
          this.title = this.formData[this.currentRecordIndex].templateName;
          break;
      }
    },
    // 切换模式重置控件宽度
    resetTableWidth(close) {
      for (const k in this.$refs) {
        if (["ControlTable", "ControlImage"].includes(k)) {
          const ref = this.$refs[k];
          ref.length &&
            ref.forEach((x) => {
              x.customFn(close);
            });
        }
      }
    },
    // 关闭页面回调
    handleClose() {
      if (this.opacity) {
        this.$emit("update:dialogFormVisible", false);
      }
      if (this.copyPageViewMode === "print") {
        this.$emit("update:dialogFormVisible", false);
        return;
      }
      if (this.pageViewMode2 === "print") {
        this.pageViewMode2 = this.copyPageViewMode;
        this.toggleConfigByPageViewMode();
        this.tableLen = this.tableLen2;
        this.tableLen2 &&
          ((this.tableLoad = true), (this.loadText = "表格加载中..."));
        this.resetTableWidth(true);

        // if (this.$refs.ControlTable?.length) {
        //   this.$refs.ControlTable.forEach((x) => {
        //     x.customFn();
        //   });
        // }
        return;
      }
      this.$emit("update:dialogFormVisible", false);
    },
    // 获取检测人信息(签名)
    getUser(name = "") {
      return new Promise((resolve) => {
        getUserListNoPage({ name }).then((res) => {
          resolve(res);
        });
      });
    },
  },
};
</script>

<style lang="scss">
.divideInside {
  .image {
    display: flex;
    flex-direction: column-reverse;
    align-items: center !important;
    width: 100%;
    .control-title {
      max-width: none !important;
    }
    .control-content {
      ul {
        li {
          img {
            max-width: 100% !important;
            max-height: 100% !important;
            vertical-align: top !important;
          }
        }
      }
    }
  }
}
.printClass {
  .el-radio__inner {
    display: none;
  }

  .el-checkbox__inner {
    display: none;
  }
}

#pdfDom {
  .el-tag {
    background-color: transparent !important;
    border-width: 0px;
    color: #000;
  }
}

.base-dialog {
  &.print {
    .el-dialog {
      .el-dialog__header {
        .el-dialog__title {
          font-weight: bold;
        }
      }
    }

    .print-header,
    .print-title {
      span {
        display: block;
        font-size: 24px;
        font-family: "\u5b8b\u4f53";
        color: #232638;
        line-height: 24px;
        padding: 16px 0;
        font-weight: 400;

        &:first-child {
          padding-bottom: 0;
          font-weight: bold;
          font-family: "SimHei";
          font-size: 29px;
          line-height: 29px;
        }
      }
    }

    #pdfDom {
      width: calc(100% - 200px);
      margin: 0 auto 40px;
      box-shadow: 0px 12px 24px 6px rgba(0, 0, 0, 0.03),
        0px 3px 28px 0px rgba(0, 0, 0, 0.05),
        0px 6px 16px -8px rgba(0, 0, 0, 0.08);
      padding: 20px 80px 0px 80px;

      .record-edit-form-container {
        position: relative;

        &::after {
          content: "";
          width: 100%;
          height: 100%;
          position: absolute;
          left: 0;
          top: 0;
          background-color: transparent;
          z-index: 98;
        }

        .record-edit-form-container_main {
          padding: 0 !important;

          .target-card-item {
            overflow: hidden;

            .control-content {
              margin-right: 0 !important;
            }
          }
        }
      }
    }
  }

  &.zip {
    opacity: 0;
  }
}
</style>

<style lang="scss" scoped>
.Eln_flex {
  display: flex;
  align-items: center;
  align-content: flex-start;
  justify-content: space-between;
  flex-wrap: wrap;
}

::v-deep .el-dialog {
  .el-dialog__body {
    height: calc(100% - 72px - 64px);
    padding: 0 !important;

    .print-download {
      @extend .Eln_flex;
      // position: absolute;
      justify-content: flex-start;
      margin: 10px 0;

      & > div {
        font-size: 0;
        margin-left: 20px;
        cursor: pointer;

        &.arrow {
          margin: 0;
          position: fixed;
          top: 50%;

          &.right {
            right: calc(50% - 1180px / 2 + 26px);
            transform: translateY(-50%);
          }

          &.left {
            transform: translateY(-50%) rotate(180deg);
            left: calc(50% - 1180px / 2 + 26px);
          }
        }

        span {
          display: block;
          font-size: 14px;
          line-height: 18px;
        }
      }
    }

    #pdfDom {
      &.height100 {
        height: 100%;
      }

      &.print {
        border: none;
        box-sizing: border-box;

        * {
          font-family: "Microsoft Yahei";
          font-weight: 600;
        }

        .record-edit-form-container_main {
          .target-card-item {
            .control-title {
              color: #000 !important;
            }

            .control-content {
              label {
                font-family: "Microsoft Yahei";
                font-weight: bold;
              }
            }
          }
        }

        .control-content .el-input .el-input__inner,
        .el-form-item__content .el-input .el-input__inner {
          padding-top: 10px;
        }

        .el-radio .el-radio__input .el-radio__inner {
          &::after {
            margin-top: 2px;
            margin-left: 2px;
          }
        }

        .el-checkbox.is-checked .el-checkbox__input .el-checkbox__inner {
          &::after {
            transform: rotate(45deg) scale(0.8);
            border-color: #000;
          }
        }
      }

      .record-edit-form-container {
        height: 100%;

        .record-edit-form-container_aside {
          box-sizing: border-box;
          padding: 24px;
          background-color: #ecf0f7;
          overflow: hidden;
          overflow-y: auto;

          & > .system-user-form {
            .el-form-item {
              .el-form-item__label {
                height: 16px;
                font-size: 12px;
                font-family: "Microsoft YaHei";
                color: #666666;
                line-height: 16px;
                margin-top: 9px;
              }

              .el-date-editor > .el-input__inner {
                // border: none;
                padding-right: 15px;
              }
            }
          }
        }

        .record-edit-form-container_main {
          @extend .Eln_flex;
          padding: 0 16px;
          min-height: 600px;
          // padding-bottom: 20px;
          justify-content: flex-start;
          overflow: auto;

          & > .target-card-item {
            margin-top: 18px;

            // 各控件基础样式
            .control {
              display: flex;
              align-items: center;
              box-sizing: border-box;

              &.flex-start {
                align-items: flex-start;
              }

              &.image {
                align-items: flex-start;

                & > .control-title {
                  margin-top: 20px;
                  max-width: 100px;
                  height: auto;

                  & > .title-label {
                    text-align: left;
                  }
                }

                & > .control-operate {
                  margin-top: 4px;
                }
              }

              & > * {
                flex-shrink: 0;
              }

              & > .control-title {
                // width: 80px;
                height: auto;
                font-size: 12px;
                font-family: "Microsoft YaHei";
                color: #666666;
                line-height: 24px;
                //line-height: auto;
                display: flex;
                align-items: center;
                justify-content: flex-end;

                & > .title-icon {
                  color: red;
                  padding-right: 3px;
                }

                & > .title-label {
                  text-align: center;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: none;
                }
              }

              .control-content {
                flex: 1;
                margin-right: 52px;
                margin-left: 10px;
                position: relative;

                &.validateError {
                  .el-input > .el-input__inner,
                  .el-textarea > .el-textarea__inner {
                    border-color: #ff4949;
                  }
                }

                .control-validate-error {
                  position: absolute;
                  top: 100%;
                  left: 0;
                  padding-top: 2px;
                  color: #ff4949;
                  font-size: 12px;
                  line-height: 1;
                }
              }
            }

            &.readonly {
              .card-item.control {
                min-height: 29px;

                &:hover {
                  & > .control-operate {
                    display: block;
                  }
                }

                & > .control-content {
                  .el-input .el-input__inner,
                  .el-textarea .el-textarea__inner {
                    border-color: #dcdfe6 !important;
                  }

                  .el-input.el-date-editor {
                    width: 100%;
                  }

                  .el-select {
                    .el-select__tags {
                      height: auto;

                      .el-tag__close {
                        display: none;
                      }
                    }
                  }
                }

                & > .control-operate {
                  display: none;
                }
              }
            }

            &.preview {
              cursor: default !important;

              .control-content {
                flex: 1;

                & > .el-select {
                  width: 100%;
                }
              }
            }

            &.showpdf {
              .el-radio__inner {
                display: none;
              }

              .el-checkbox__inner {
                display: none;
              }

              .el-input {
                .el-input__inner {
                  border: none;
                }

                .el-input__suffix {
                  display: none;
                }
              }

              .el-textarea > .el-textarea__inner {
                border: none;
              }

              .el-date-editor .el-input__prefix {
                display: none;
              }

              .el-input-number {
                span {
                  display: none;
                }

                input {
                  background-color: #fff;
                }
              }

              .control-content.image,
              .control-content.table {
                margin-right: 0;
              }

              .base-upload {
                width: 100%;

                .el-upload-list {
                  li {
                    width: 100%;
                    height: auto;
                  }
                }

                .el-upload {
                  display: none;
                }
              }
            }
          }
        }
      }

      .dialog-footer {
        .footer-title {
          display: inline-block;
          width: 100%;
          box-sizing: border-box;
          padding: 13px 16px;
          line-height: 14px;
          font-size: 14px;
          text-align: left;
          background-color: #f1f8ff;
        }

        ul {
          display: flex;
          justify-content: space-between;
          flex-wrap: wrap;

          & > li {
            width: calc(100% / 4);
            box-sizing: border-box;
            padding: 10px 16px 10px;
            text-align: left;
            display: flex;
            align-items: center;

            &.jianceren {
              span {
                line-height: 22px;
              }

              & > .jianceren-nodename {
                flex-shrink: 0;
              }
            }

            & > .verify-item {
              display: flex;
              width: 100%;
              justify-content: flex-start;
              flex-wrap: wrap;
              box-sizing: border-box;

              & > .verify-account {
                display: flex;
                width: 100%;
                overflow: hidden;
                align-items: center;

                span {
                  display: block;
                }

                img {
                  height: 85px;
                }
              }

              & > span {
                display: inline-block;
                white-space: pre-wrap;
                word-break: break-all;
                max-width: 112px;
              }
            }
          }
        }
      }
    }
  }

  .el-dialog__footer {
    padding: 16px !important;

    .el-button {
      width: 70px;

      & + .el-button {
        margin-left: 30px !important;
      }
    }
  }
}

::v-deep .el-dialog {
  .el-dialog__body {
    #pdfDom {
      .record-edit-form-container {
        .record-edit-form-container_main {
          .el-form {
            border-bottom: 1px solid #000;

            .el-form-item {
              .el-form-item__label {
                font-size: 16px;
                font-family: "Microsoft YaHei";
                color: #666;
              }

              .el-form-item__content div {
                text-align: left;
                font-size: 16px;
                font-family: "Microsoft YaHei";
                color: #666;
              }
            }
          }

          & > .target-card-item {
            margin: 18px 20px 0 20px;

            &:last-child {
              margin-bottom: 18px;
            }

            // 各控件基础样式
            .control {
              display: flex;
              align-items: center;
              box-sizing: border-box;

              & > .control-title {
                // width: 80px;
                height: 16px;
                font-size: 16px;
                font-family: "Microsoft YaHei";
                color: #666;
                line-height: 16px;
                display: flex;
                align-items: center;
                justify-content: flex-end;

                & > .title-icon {
                  color: red;
                  padding-right: 3px;
                }

                & > .title-label {
                  text-align: center;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: inherit;
                }
              }

              & > .control-content {
                font-size: 16px;
                font-family: "Microsoft YaHei";
                color: #666;
              }
            }
          }

          .el-upload-list--picture-card {
            display: flex;
            width: 100%;
            flex-wrap: wrap;
          }

          .image.half {
            .el-upload-list li {
              height: 545px !important;
            }
          }

          .el-upload-list li {
            width: 100% !important;
            // 通过计算得到此高度 A4纸固定高度841.89， rate = contentWidth / elementWidth;
            // contentWidth=550， elementWidth: this.$refs.print的宽度
            height: 1100px !important;
            margin: 11px 10px 0;
          }
        }
      }
    }
  }
}

::v-deep .el-dialog {
  .el-dialog__body {
    .printStyle {
      .record-edit-form-container {
        .record-edit-form-container_main {
          .el-form {
            border-bottom: 1px solid #000;

            .el-form-item {
              .el-form-item__label {
                font-size: 16px;
                font-family: "\u5b8b\u4f53" !important;
                color: #000 !important;
              }

              .el-form-item__content div {
                text-align: left;
                font-size: 16px !important;
                font-family: "\u5b8b\u4f53" !important;
                color: #000 !important;
              }
            }
          }

          & > .target-card-item {
            margin: 18px 20px 0 20px;

            // 各控件基础样式
            .control {
              &.flex-start {
                align-items: center !important;
              }

              & > .control-title {
                // width: 80px;
                height: 18px;
                font-size: 16px;
                font-family: "\u5b8b\u4f53" !important;
                color: #000 !important;
                line-height: 18px !important;
                display: flex;
                align-items: center;
                justify-content: flex-end;

                & > .title-icon {
                  color: red;
                  padding-right: 3px;
                }

                & > .title-label {
                  text-align: right;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                }
              }

              & > .control-content {
                font-size: 16px !important;
                font-family: "\u5b8b\u4f53" !important;
                color: #000 !important;
              }
            }
          }

          .el-upload-list--picture-card {
            display: flex;
            width: 100%;
            flex-flow: wrap;
          }

          .el-upload-list li {
            width: 45% !important;
            height: auto;
            margin: 11px 10px 0;
          }
        }
      }
    }
  }
}

.pdf-footer {
  font-weight: bold;
  padding: 15px 0 30px;
  width: 100%;
  border-top: 1px solid rgba(0, 0, 0, 0.85);
  position: fixed;
  bottom: 0;
  left: 0;
  margin-bottom: 20px;
  z-index: -1;
  display: flex;
  align-items: center;
  justify-content: center;

  & > * {
    font-size: 16px;
    line-height: 16px;
  }
}
</style>
